using MediatR;
using Medical.Domain;
using Medical.Infrastructrue.Interfaces;
using Medical.WriteApi.Appcontext.Command;
using Yitter.IdGenerator;

namespace Medical.WriteApi.Appcontext.CommandHandler
{
	public class AssignRolesToUserCommandHandler : IRequestHandler<AssignRolesToUserCommand, bool>
	{
		private readonly IBaseRepository<UserRole> _userRoleRepo;

		public AssignRolesToUserCommandHandler(IBaseRepository<UserRole> userRoleRepo)
		{
			_userRoleRepo = userRoleRepo;
		}

		public async Task<bool> Handle(AssignRolesToUserCommand request, CancellationToken cancellationToken)
		{
			// 删除旧的角色关联
			var oldUserRoles = _userRoleRepo.GetAll()
				.Where(x => ((UserRole)x).UserId == request.UserId)
				.Select(x => (UserRole)x)
				.ToList();
			
			if (oldUserRoles.Any())
			{
				await _userRoleRepo.DeleteRangeAsync(oldUserRoles);
			}

			// 添加新的角色关联
			if (request.RoleIds != null && request.RoleIds.Any())
			{
				var newUserRoles = request.RoleIds.Distinct()
					.Select(roleId => new UserRole
					{
						UserRoleId = YitIdHelper.NextId(),
						UserId = request.UserId,
						RoleId = roleId
					})
					.ToList();
				
				if (newUserRoles.Any())
				{
					await _userRoleRepo.AddRangeAsync(newUserRoles);
				}
			}

			return true;
		}
	}
}

